package com.pjchat.pjchatclient.receiver;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;

import javax.swing.JOptionPane;

import com.ita.im.model.Unit;
import com.pjchat.pjchatclient.frame.MyClientFrame;
import com.pjchat.pjchatclient.handler.BasicHandler;
import com.pjchat.pjchatclient.handlerfactory.HandlerFactory;
import com.pjchat.pjchatclient.util.JsonUtil;

public class ClientReceiverRunnable implements Runnable {
	private MyClientFrame myFrame;
	private BasicHandler handler;
	private BufferedReader br;
	private BufferedWriter bw;

	public ClientReceiverRunnable(MyClientFrame myFrame, BufferedReader br,
			BufferedWriter bw) throws IOException {
		this.myFrame = myFrame;
		this.br = br;
		this.bw = bw;
	}

	@Override
	public void run() {
		while (true) {
			Unit unit = null;
			try {
				try {
					unit = JsonUtil.jsonObjectToUnit(br.readLine());
				} catch (NullPointerException e) {
					int a = JOptionPane.NO_OPTION;
					while (a != 0) {
						a = JOptionPane.showConfirmDialog(null,
								"Can't connect to server,please try later",
								"温馨提示", JOptionPane.YES_NO_OPTION);
						switch (a) {
						case JOptionPane.YES_OPTION:
							System.exit(0);
							break;
						default:
							break;
						}
					}
					e.printStackTrace();
				}
			} catch (IOException e) {
				JOptionPane.showMessageDialog(null, "Big server is closed");
				System.exit(0);
				e.printStackTrace();
				break;
			}
			if (unit != null) {
				handler = HandlerFactory.produce(unit.getType());
				handler.doResponse(myFrame, unit, br, bw);
			}

		}
	}

}
